package com.bw.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.bw.domain.Role;
import com.bw.domain.User;
import com.bw.exception.MyRuntimeException;
import com.bw.service.UserService;
import com.bw.utils.R;
import com.bw.utils.esypoi.ExportsUtil;
import com.bw.utils.esypoi.ImportsUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Author: Wrj
 * @Date: 2025/3/9 09:38
 * @Description:
 **/
@Controller
@RequestMapping("user")
public class UserController {
    
    @Autowired
    UserService userService;


    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 导出所选的内容
     * @param response
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("exportExcel2")
    public R exportExcel2(HttpServletResponse response,String ids){
        List<User> userList=userService.listByIds(ids);
        String exportNamm="export-"+DateUtil.today()+"-"+RandomUtil.randomNumbers(4);
        ExportsUtil.exports(response, User.class,userList,"学生信息","学生列表",exportNamm);

        return R.OK();
    }

    /**
     * 把数据全部导入
     * @param file
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("importExcel")
    public R importExcel(MultipartFile file) throws IOException {
        //判断是否为空
        if (file==null || file.isEmpty()){
            return R.ERROR(500,"请选择上传文件");
        }
        try {

            //把文件上传到一个临时目录
            File temp = File.createTempFile("temp", file.getOriginalFilename());
            //把文件写入上传的文件
            file.transferTo(temp);

            List<User> userList = ImportsUtil.imports(temp, User.class, 1, 1);

            userService.addBach(userList);
            return R.OK();
        }catch (MyRuntimeException e){
            e.printStackTrace();
            throw new MyRuntimeException("上传失败");
        }

    }

    /**
     * 把数据全部导出
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("exportExcel")
    public R exportExcel(HttpServletResponse response){

        //查询所有导出的数据
        List<User> userList=userService.listUser();
        String exportFileName="export-"+ DateUtil.today()+"-"+"-"+ RandomUtil.randomNumbers(4);
        //调用工具类
        ExportsUtil.exports(response, User.class,userList,"用户列表","用户信息",exportFileName);
        return R.OK();
    }


    /**
     * 查询所有角色名称
     * @return
     */
    @ResponseBody
    @RequestMapping("listRoleName")
    public R listRoleName(){
        List<Role> roleList=userService.listRoleName();
        return R.OK(roleList);
    }

    /**
     * 校验名称是否重复
     * @param username
     * @return
     */
    @ResponseBody
    @RequestMapping("checkedUsername")
    public R checkedUsername(String username){
        int i =userService.checkedUsername(username);
        return i>0?R.ERROR(404,"名称重复"):R.OK();
    }


    /**
     * 去往添加页面
     * @return
     */
    @RequestMapping("toadd")
    public String toadd(){
        return "user/add";
    }


    /**
     * 执行添加
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("add")
    public R add(User user){

        if (StringUtils.isEmpty(user.getAccount())){
            return R.ERROR(404,"用户姓名不能为空");
        }
        if (StringUtils.isEmpty(user.getUsername())){
            return R.ERROR(404,"账号不能为空");
        }
        if (StringUtils.isEmpty(user.getPhone())){
            return R.ERROR(404,"手机号不能为空");
        }
        if (StringUtils.isEmpty(user.getPassword())){
            return R.ERROR(404,"密码不能为空");
        }
        if (StringUtils.isEmpty(user.getEmail())){
            return R.ERROR(404,"电子邮箱不能为空");
        }
        if (StringUtils.isEmpty(user.getRoleId())){
            return R.ERROR(404,"所属角色能为空");
        }

        int i =userService.checkedUsername(user.getUsername());
        if (i>0){
            return R.ERROR(404,"用户名重复");
        }


        boolean b =userService.add(user);
        return b?R.OK():R.ERROR(404,"添加失败");
    }


    /**
     * 去往列表页面
     * @return
     */
    @RequestMapping("tolist")
    public String tolist(){
        return "user/list";
    }


    @ResponseBody
    @RequestMapping("list")
    public R list(User user, Integer page, Integer limit, HttpSession session){

        //从session获取登录人信息
        User sessionuser = (User) session.getAttribute("user");
        //获取当前登录人所拥有的角色
        List<Role> roleList = (List<Role>) redisTemplate.opsForValue().get("role" + sessionuser.getUserId());

        String authId="";
        String roleName="";
        for (Role role : roleList) {
            authId+=","+role.getRoleId();
            roleName+=role.getRoleName();
        }
        authId=authId.substring(1);
        if (!roleName.equals("超级管理员")){
            //设置权限id
            user.setAuthId(authId);
        }


        PageHelper.startPage(page,limit);
        List<User> userList=userService.list(user);

        PageInfo<User> userPageInfo = new PageInfo<>(userList);

        return R.OK(userPageInfo);
    }
}
